import React, { useState, useEffect, useMemo } from "react";
import { Observable, interval } from "rxjs";
import { take } from "rxjs/operators";

// 自定义 Hook：将 Observable 转换为 React 状态
function useObservable<T>(observable: Observable<T>) {
  const [value, setValue] = useState<T | null>(null);

  useEffect(() => {
    const subscription = observable.subscribe({
      next: setValue,
      error: (err) => console.error("Error:", err),
      complete: () => console.log("Observable completed"),
    });

    return () => subscription.unsubscribe(); // 清理订阅
  }, [observable]);

  return value;
}

// 使用自定义 Hook 的组件
const App = () => {
  // 使用 useMemo 缓存 Observable，避免每次渲染都创建新的 Observable
  const count$ = useMemo(() => interval(1000).pipe(take(10)), []); 
  const count = useObservable(count$);

  return (
    <div>
      <h1>Count: {count}</h1>
    </div>
  );
};

export default App;
